package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.constant.BusinessStatusConstants;
import com.qk.constant.ClueStatusConstants;
import com.qk.constant.ClueTrackRecordType;
import com.qk.dto.clue.*;
import com.qk.entity.Business;
import com.qk.entity.Clue;
import com.qk.entity.ClueTrackRecord;
import com.qk.entity.User;
import com.qk.enums.ParamEnum;
import com.qk.exception.CommonException;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.mapper.TrackRecordMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.ClueService;
import com.qk.utils.CurrentUserContextHolders;
import com.qk.vo.clue.CluePoolVO;
import com.qk.vo.clue.ClueQueryVO;
import com.qk.vo.clue.ClueVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 *
 * @author lyl
 * @created 2025/10/13 19:52
 * @description
 *
 */
@Service
@SuppressWarnings("all")
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TrackRecordMapper trackRecordMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private ClueMapper ClueMapper;

    @Override
    public PageResult<CluePoolVO> getCluePool(CluePoolDTO cluePoolDTO) {
        Page<CluePoolVO> list = ClueMapper.getCluePool(Page.of(cluePoolDTO.getPage(),cluePoolDTO.getPageSize()),cluePoolDTO);
        return PageResult.<CluePoolVO>builder()
                .total(Long.valueOf(list.getTotal()).intValue())
                .rows(list.getRecords())
                .build();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void falseClue(Integer id, FalseClueDTO falseClueDTO) {
        Clue clue = this.baseMapper.selectById(id);
        if (ObjectUtil.isEmpty(clue)){
            CommonException.throwCommonException(ParamEnum.PARAM_NOT_EXIST);
        }
        clue.setStatus(ClueStatusConstants.FAKE_CLUE);
        clue.setUpdateTime(LocalDateTime.now());
        clue.setNextTime(null);
        this.baseMapper.update(Wrappers.lambdaUpdate(Clue.class)
                .set(Clue::getStatus, clue.getStatus())
                .set(Clue::getNextTime, clue.getNextTime())
                .set(Clue::getUpdateTime, clue.getUpdateTime())
                .eq(Clue::getId, id));
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(clue, ClueTrackRecord.class);
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(clue.getId());
        clueTrackRecord.setRecord(falseClueDTO.getRemark());
        clueTrackRecord.setType(ClueTrackRecordType.FAKE);
        clueTrackRecord.setFalseReason(falseClueDTO.getReason());
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        trackRecordMapper.insert(clueTrackRecord);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void toBusiness(Integer id) {
        Clue clue = this.baseMapper.selectById(id);
        if (ObjectUtil.isEmpty(clue)){
            CommonException.throwCommonException(ParamEnum.PARAM_NOT_EXIST);
        }
        clue.setStatus(ClueStatusConstants.CONVERT_TO_BUSINESS);
        clue.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(clue);
        Business business = BeanUtil.copyProperties(clue, Business.class);
        business.setId(null);
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        business.setUserId(null);
        business.setClueId(clue.getId());
        business.setNextTime(null);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        businessMapper.insert(business);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateClue(UpdateClueInfoDTO updateClueInfoDTO) {
        Clue clue = BeanUtil.copyProperties(updateClueInfoDTO, Clue.class);
        clue.setUpdateTime(LocalDateTime.now());
        if (clue.getStatus() == ClueStatusConstants.WAIT_FOLLOW_UP){
            clue.setStatus(ClueStatusConstants.FOLLOW_UP);
        }
        this.baseMapper.updateById(clue);
        ClueTrackRecord clueTrackRecord = BeanUtil.copyProperties(updateClueInfoDTO, ClueTrackRecord.class);
        clueTrackRecord.setCreateTime(LocalDateTime.now());
        clueTrackRecord.setId(null);
        clueTrackRecord.setClueId(clue.getId());
        clueTrackRecord.setType(ClueTrackRecordType.NORMAL);
        clueTrackRecord.setUserId(CurrentUserContextHolders.get());
        trackRecordMapper.insert(clueTrackRecord);
    }

    @Override
    public ClueVO getClueInfoById(Integer id) {
        Clue clue = this.getById(id);
        if (ObjectUtil.isEmpty(clue)){
            CommonException.throwCommonException(ParamEnum.PARAM_NOT_EXIST);
        }
        User user = userMapper.getUserById(clue.getUserId());
        List<ClueTrackRecord> trackRecords = trackRecordMapper.selectList(Wrappers.lambdaQuery(ClueTrackRecord.class).eq(ClueTrackRecord::getClueId,id));
        ClueVO clueVO = BeanUtil.copyProperties(clue, ClueVO.class);
        List<ClueVO.TrackRecordVO> trackRecordVOS = trackRecords.stream().map(trackRecord -> {
            ClueVO.TrackRecordVO trackR =  BeanUtil.copyProperties(trackRecord, ClueVO.TrackRecordVO.class);
            trackR.setAssignName(user.getName());
            return trackR;
        }).toList();
        clueVO.setTrackRecords(trackRecordVOS);
        return clueVO;
    }

    @Override
    public void assign(Integer clueId, Integer userId) {
        this.update(Wrappers.lambdaUpdate(Clue.class)
                .set(Clue::getUserId, userId)
                .set(Clue::getStatus, ClueStatusConstants.WAIT_FOLLOW_UP)
                .eq(Clue::getId, clueId));
    }
    @Override
    public PageResult<ClueQueryVO> getListPage(ClueQueryDTO clueDTO) {
        Page<ClueQueryVO> list = this.baseMapper.getListPage(Page.of(clueDTO.getPage(), clueDTO.getPageSize()),clueDTO);
        return PageResult.<ClueQueryVO>builder()
                .total(Long.valueOf(list.getTotal()).intValue())
                .rows(list.getRecords())
                .build();
    }
    @Override
    public void addClue(ClueDTO clueDTO) {
        if(ObjectUtil.isEmpty(clueDTO.getPhone()) || clueDTO.getPhone().isEmpty() || ObjectUtil.isEmpty(clueDTO.getChannel())){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Clue clue = BeanUtil.copyProperties(clueDTO, Clue.class);
        clue.setCreateTime(LocalDateTime.now());
        clue.setUpdateTime(LocalDateTime.now());
        clue.setStatus(ClueStatusConstants.WAIT_ALLOCATION);
        this.save(clue);
    }
}
